package com.yunnuo.system.shiro.service;


import com.yunnuo.system.domain.User;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 盐值密码校验生成
 * Created by 魏洪福(15064000912@163.com) on  2018/5/25.
 */
@Component
public class PasswordService
{

    @Autowired
    private CacheManager cacheManager;

    private Cache<String, AtomicInteger> loginRecordCache;

    @Value(value = "${user.password.maxRetryCount}")
    private String maxRetryCount;

    @PostConstruct
    public void init()
    {
        loginRecordCache = cacheManager.getCache("loginRecordCache");
    }

    public void validate(User user, String password) throws Exception {
        String loginName = user.getLoginName();
        AtomicInteger retryCount = loginRecordCache.get(loginName);
            if (retryCount == null)
            {
                retryCount = new AtomicInteger(0);
                loginRecordCache.put(loginName, retryCount);
            }
            if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue())
            {
                throw new Exception("用户名密码出错");
            }

            if (!matches(user, password))
            {
                loginRecordCache.put(loginName, retryCount);
                throw new Exception("用户名密码出错");
            }
            else
            {
                clearLoginRecordCache(loginName);
            }

    }

    public boolean matches(User user, String newPassword)
    {
        return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
    }

    public void clearLoginRecordCache(String username)
    {
        loginRecordCache.remove(username);
    }

    public String encryptPassword(String username, String password, String salt)
    {
        return new Md5Hash(username + password + salt).toHex().toString();
    }

    public static void main(String[] args)
    {
        System.out.println(new PasswordService().encryptPassword("yunnuo", "yunnuo", "111111"));
    }
}
